package com.jxc.dao.impl;

import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.transaction.annotation.Transactional;
import com.jxc.dao.TbEmployeeDAO;
import com.jxc.dao.TbRoleDAO;
import com.jxc.entity.TbEmployee;
import com.jxc.entity.TbEmployeeRole;
import com.jxc.entity.TbRole;

/**
 * Data access object (DAO) for domain model class TbEmployee.
 * 
 * @see com.TbEmployee
 * @author MyEclipse Persistence Tools
 */
@Transactional
public class TbEmployeeDAOImpl implements TbEmployeeDAO {
	@Resource
	private SessionFactory sessionFactory;
	@Resource
	private TbEmployeeDAO tbEmployeeDAO;
	@Resource
	private TbRoleDAO tbRoleDAO;

	private static final Log log = LogFactory.getLog(TbEmployeeDAOImpl.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#save(com.jxc.entity.TbEmployee)
	 */

	public void saveEmployeeAndRole(TbEmployee t, String username, int a) {
		log.debug("saving TbEmployee instance");
		try {
			sessionFactory.getCurrentSession().save(t);
			List list = this.tbEmployeeDAO.findByUserName(username);
			TbEmployee t2 = (TbEmployee) list.get(0);
			TbEmployeeRole t1 = new TbEmployeeRole();
			TbRole tbRole = this.tbRoleDAO.findById(a);
			t1.setTbRole(tbRole);
			t1.setTbEmployee(t2);
			sessionFactory.getCurrentSession().save(t1);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public boolean save(TbEmployee transientInstance) {
		log.debug("saving TbEmployee instance");
		boolean bool = false;
		try {
			sessionFactory.getCurrentSession().save(transientInstance);
			log.debug("save successful");
			bool = true;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			bool = true;
			throw re;
		}
		return bool;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#delete(com.jxc.entity.TbEmployee)
	 */
	public void delete(TbEmployee persistentInstance) {
		log.debug("deleting TbEmployee instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findById(java.lang.Integer)
	 */
	public TbEmployee findById(java.lang.Integer id) {
		log.debug("getting TbEmployee instance with id: " + id);
		System.out.println(id + "___________");
		try {
			TbEmployee instance = (TbEmployee) sessionFactory
					.getCurrentSession().get(TbEmployee.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByExample(com.jxc.entity.TbEmployee)
	 */
	public List findByExample(TbEmployee instance) {
		log.debug("finding TbEmployee instance by example");
		try {
			List results = sessionFactory.getCurrentSession().createCriteria(
					TbEmployee.class).add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByProperty(java.lang.String,
	 *      java.lang.Object)
	 */
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding TbEmployee instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from TbEmployee as model where model."
					+ propertyName + "= ?";
			Query queryObject = sessionFactory.getCurrentSession().createQuery(
					queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByCompanyId(java.lang.Object)
	 */
	public List findByCompanyId(Object companyId) {
		return findByProperty(COMPANY_ID, companyId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByUserName(java.lang.Object)
	 */
	public List findByUserName(Object userName) {
		return findByProperty(USER_NAME, userName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByPwd(java.lang.Object)
	 */
	public List findByPwd(Object pwd) {
		return findByProperty(PWD, pwd);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByRole(java.lang.Object)
	 */
	public List findByRole(Object role) {
		return findByProperty(ROLE, role);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByDept(java.lang.Object)
	 */
	public List findByDept(Object dept) {
		return findByProperty(DEPT, dept);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByTitle(java.lang.Object)
	 */
	public List findByTitle(Object title) {
		return findByProperty(TITLE, title);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByName(java.lang.Object)
	 */
	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByNumber(java.lang.Object)
	 */
	public List findByNumber(Object number) {
		return findByProperty(NUMBER, number);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findBySex(java.lang.Object)
	 */
	public List findBySex(Object sex) {
		return findByProperty(SEX, sex);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByAge(java.lang.Object)
	 */
	public List findByAge(Object age) {
		return findByProperty(AGE, age);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByMobile(java.lang.Object)
	 */
	public List findByMobile(Object mobile) {
		return findByProperty(MOBILE, mobile);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByPhone(java.lang.Object)
	 */
	public List findByPhone(Object phone) {
		return findByProperty(PHONE, phone);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByEmail(java.lang.Object)
	 */
	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByAddr(java.lang.Object)
	 */
	public List findByAddr(Object addr) {
		return findByProperty(ADDR, addr);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByPeopleType(java.lang.Object)
	 */
	public List findByPeopleType(Object peopleType) {
		return findByProperty(PEOPLE_TYPE, peopleType);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByAddrRegister(java.lang.Object)
	 */
	public List findByAddrRegister(Object addrRegister) {
		return findByProperty(ADDR_REGISTER, addrRegister);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByNation(java.lang.Object)
	 */
	public List findByNation(Object nation) {
		return findByProperty(NATION, nation);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByInputUser(java.lang.Object)
	 */
	public List findByInputUser(Object inputUser) {
		return findByProperty(INPUT_USER, inputUser);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findByFlag(java.lang.Object)
	 */
	public List findByFlag(Object flag) {
		return findByProperty(FLAG, flag);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#findAll()
	 */
	public List findAll() {
		log.debug("finding all TbEmployee instances");
		try {
			String queryString = "from TbEmployee";
			Query queryObject = sessionFactory.getCurrentSession().createQuery(
					queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#merge(com.jxc.entity.TbEmployee)
	 */
	public TbEmployee merge(TbEmployee detachedInstance) {
		log.debug("merging TbEmployee instance");
		try {
			TbEmployee result = (TbEmployee) sessionFactory.getCurrentSession()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#attachDirty(com.jxc.entity.TbEmployee)
	 */
	public boolean attachDirty(TbEmployee instance) {
		log.debug("attaching dirty TbEmployee instance");
		boolean bool = false;
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
			bool = true;
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			bool = false;
			throw re;

		}
		return bool;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.dao.impl.TbEmployeeDAO#attachClean(com.jxc.entity.TbEmployee)
	 */
	public void attachClean(TbEmployee instance) {
		log.debug("attaching clean TbEmployee instance");
		try {
			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void delete(Integer id) {
		log.debug("saving Actionurl instance");
		try {
			sessionFactory.getCurrentSession().delete(
					sessionFactory.getCurrentSession().load(TbEmployee.class,
							id));
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/*
	 * 查询员工列表
	 */
    String  sql="";
	public List QueryEmployee(String name, String names, String dept,
			int start, int limit, String city, String district, String whereStr) {
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("select  tb_employee.name,tb_employee.userName,tb_company.short_name,tb_employee.dept,tb_employee.mobile,tb_employee.sex,tb_employee.birth,tb_employee.addr, ");
			sb.append("tb_employee.email,tb_employee.dt_update,tb_employee.id,tb_employee_role.role_id,tb_employee.flag,tb_company.province,tb_company.city, ");
			sb.append("tb_company.district  FROM tb_employee left join  tb_company  on  tb_employee.company_id=tb_company.id left    join  tb_employee_role on tb_employee.id=tb_employee_role.user_id ");
			sb.append("where 1=1 and  tb_employee.flag in(1,0)");
			if (name.length() > 0) {
				sb.append(" and tb_employee.company_id ='%" + name + "%' ");
			}
			if (names.length() > 0) {
				sb.append("and tb_employee.userName like'%" + names + "%' ");
			}
			if (dept.length() > 0) {
				sb.append("and tb_employee.dept like '" + dept + "'");
			}
			if (null != city) {
				if (!city.equals("")) {
					sb.append("and tb_company.city = '" + city + "' ");
				}
			}
			if (null != district) {
				if (!district.equals("")) {
					sb.append(" and tb_company.district= '" + district + "' ");
				}
			}
			// 1:admin 5:省分司 6:地市公司 23:县分司 2 接机点 3 维修点 4:客户经理
			// tb_employee_role.role_id
			if (!whereStr.equals("")) {
				String[] strTemp=whereStr.split(",");
				if (strTemp[0].equals("1")) {//1:admin
					// HQL=HQL+" AND a.tbRole.roleId=23 or a.tbRole.roleId=2 or
					// a.tbRole.roleId=3 or a.tbRole.roleId=4 or
					// a.tbRole.roleId=1 or a.tbRole.roleId=5 or
					// a.tbRole.roleId=6 ";
					

				} else {
					if(strTemp[0].equals("5"))// 5:省分司
					{
						sb.append(" and ( tb_employee_role.role_id in(6,23,2,3,4)");
					}
				    else if (strTemp[0].equals("6")) // 地市公司
					{
						sb.append(" and ( tb_employee_role.role_id in(23,2,3,4)");
					} else if (strTemp[0].equals("23")) // 县分司
					{
						sb.append(" and ( tb_employee_role.role_id in(2,3,4) ");
					} else {
						sb.append(" and (  tb_employee_role.role_id= '" + strTemp[0]
								+ "  ' ");
					}
					
					sb.append(" or ( tb_employee_role.role_id  is null ");
					sb.append(" and  tb_employee.input_user= '"+strTemp[2]+"' ))");
				}
				
			}
			sb.append(" order by tb_employee.id asc");
			sql=sb.toString();
			return sessionFactory.getCurrentSession().createSQLQuery(
					sb.toString()).setFirstResult(start * limit).setMaxResults(
					limit).list();

		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}

	/*
	 * 统计列表数
	 * 
	 * @see com.jxc.dao.TbEmployeeDAO#QueryEmployeeTotal()
	 */
	public int QueryEmployeeTotal() {
		try {
			List list = sessionFactory.getCurrentSession().createSQLQuery(
					sql).list();
			return list != null ? list.size() : 0;
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
}